package com.polaris.live.ui.message.proxy

import android.view.View
import androidx.fragment.app.FragmentActivity
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityMessageBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog_fragment.GiftDialogFragment
import com.polaris.live.im.manager.ImManager
import com.polaris.live.im.sfs.COMMAND_SINGLE_MESSAGE
import com.polaris.live.im.sfs.SYSTEM_USER_ID
import com.polaris.live.im.sfs.TYPE_MESSAGE_GIFT
import com.polaris.live.im.sfs.bean.chat.SingleMessage
import com.polaris.live.im.sfs.bean.chat.ext.SingleMessageExtBean
import com.polaris.live.im.sfs.bean.chat.ext.SingleMessagePayloadBean
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.MessageMorePopup
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.back_resp.toUserBasicVo
import com.polaris.live.utils.StartCallProxy
import com.polaris.live.utils.image.forResultSingle
import com.polaris.live.utils.image.openGalleryDefault
import com.polaris.live.viewmodel.message.MessageViewModel

/**
 * 消息页面的点击事件代理类
 *
 * @author Created by 半仙 on 2023/9/4/004 21:12
 */
class MessageListenerProxy(
    private val otherId: Long,
    private val nickName: String?,
    private val mActivity: FragmentActivity,
    private val mBinding: ActivityMessageBinding,
    private val mViewModel: MessageViewModel,
    private val mPage: Int,
) {

    private var otherInfo: InfoOtherResp? = null
    private var mute: Boolean = false //是否禁言
    private var ban: Boolean = false  //是否封号

    init {
        mViewModel.infoOtherLiveData.observe(mActivity) { resultState ->
            parseState(resultState, {
                otherInfo = it
                mute = it.flag.mute
            }, {
                if (it.errCode == CommonConst.ErrorCode.ACCOUNT_SHUT_DOWN) { //该账号已经被关小黑屋)
                    ban = true
                }
            })

        }

        //添加对方
        mBinding.ivFollower.setOnSingleClickListener {
            mViewModel.addFollower(otherId)
        }
        //结束页面
        mBinding.icBack.setOnSingleClickListener {
            mActivity.finish()
        }
        //更多
        mBinding.moreSelect.setOnSingleClickListener {
            val otherInfo = otherInfo

            val nickname = otherInfo?.nickname ?: nickName ?: ""
            val id = otherInfo?.userId ?: otherId
            val block = otherInfo?.relation?.blocked ?: true

            XPopup.Builder(mActivity)
                .isDestroyOnDismiss(true)
                .asCustom(MessageMorePopup(mActivity, mViewModel, otherId, mute, ban, block, {
                    GlobalPopupManager.showReport(
                        mActivity, nickname,
                        mViewModel, id
                    )
                }, {
                    GlobalDialogManager.showBlackIt(mActivity, mViewModel, block, nickname, id) {
                        otherInfo?.relation?.blocked = it
                        if (it) {
                            mBinding.ivFollower.visibility = View.VISIBLE
                        }
                        if (otherInfo == null) {
                            mViewModel.getInfoUser(
                                id,
                                false,
                                UserManager.BASIC_INFORMATION,
                                UserManager.RELATIONSHIP_INFORMATION,
                                UserManager.ALBUM_INFORMATION,
                                UserManager.COVER_INFORMATION,
                                UserManager.CALL_INFORMATION,
                                UserManager.LIVE_INFORMATION
                            )
                        }
                    }
                }, {
                    mute = it
                }, {
                    ban = it
                }, {
                    mBinding.editView.setKeyboardListerState(it)
                }))
                .show()
        }
        mBinding.editView.setOnEditClickListener { resId ->
            when (resId) {
                //发送礼物
                R.id.send_gift -> {
                    mBinding.editView.setStateNormal()
                    showGiftDialog()
                }
                //发送消息
                R.id.send_message -> {
                    val text = mBinding.editView.getText()
                    if (!text.isNullOrEmpty()) {
                        mBinding.editView.cleanText()
                        onSendMessageCallback?.invoke(text)
                    }
                }
            }
        }
        mBinding.editView.setOnSelectPhotoListener {
            XPopup.Builder(mActivity)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(SelectImagePopup(mActivity, onSelectIt = { type ->
                    when (type) {
                        SelectImagePopup.CAMERA -> {
                            mBinding.editView.setStateNormal()
                            PictureSelector.create(mActivity)
                                .openCamera(SelectMimeType.ofImage())
                                .forResultSingle {
                                    mViewModel.sendImageMessage(mActivity, otherId, it)
                                }
                        }

                        else -> {
                            mBinding.editView.setStateNormal()
                            PictureSelector.create(mActivity)
                                .openGalleryDefault(1)
                                .forResultSingle {
                                    mViewModel.sendImageMessage(mActivity, otherId, it)
                                }
                        }
                    }
                }))
                .show()

        }
        //打电话
        mBinding.editView.setOnCallVideoClickListener {
            StartCallProxy.builder(mActivity).startCall(
                mViewModel,
                mPage,
                if (otherId != SYSTEM_USER_ID) UserConst.LastFrom.SINGLE else UserConst.LastFrom.SYSTEM_MESSAGE,
                LiveConst.SenderFrom.MANUAL,
                otherId,
                otherInfo?.toUserBasicVo()
            )
        }
    }

    fun showGiftDialog() {
        mGiftDialog.apply {
            setUserId(otherId, nickName)
            show(
                mActivity.supportFragmentManager,
                GiftDialogFragment.FRAGMENT_TAG
            )
        }

    }

    private val mGiftDialog: GiftDialogFragment
        get() = GiftDialogFragment(
            showType = AppConst.GiftComming.SINGLE,
            AppConst.BackpackGiftComming.MESSAGE,
            null,
            false,
            dismiss = {
                mBinding.editView.setResume(true)
            },
            sendGiftCallback = { giftSendBean ->
                val singleMessage = SingleMessage(
                    recipient = otherId,
                    content = giftSendBean.gift.id.toString(),
                    type = TYPE_MESSAGE_GIFT,
                    payload = JsonUtils.toJson(
                        SingleMessagePayloadBean(
                            giftAmount = giftSendBean.num,
                            giftBackpackId = giftSendBean.backpackId,
                            payload = giftSendBean.gift.payload
                        )
                    ),
                    ext = JsonUtils.toJson(
                        SingleMessageExtBean(
                            giftName = giftSendBean.gift.giftName,
                            giftUrl = giftSendBean.gift.pic,
                        )
                    )
                )

                ImManager.sendMessageWithAsync(mActivity, COMMAND_SINGLE_MESSAGE, singleMessage, onCompleted = {
                    if (it is AppException) {
                        if (it.errCode == CommonConst.ErrorCode.VIP_LEVEL_INSUFFICIENT) {
                            GlobalDialogManager.showInsufficientVIPLevel(
                                mActivity,
                                giftSendBean.gift.payload,
                                giftSendBean.gift.pic
                            )
                        }
                    }
                })
            })

    private var onSendMessageCallback: ((text: String) -> Unit)? = null

    fun setOnSendMessageCallback(l: (String) -> Unit) {
        onSendMessageCallback = l
    }

}